package com.quanyan.common.utils;

import java.io.*;

/**
 * @author songzj
 * @date 16/4/19-10:15
 */
public class FileUtil {


    public static void writeToFile(String content, String fileName) throws IOException {
        Writer writer = null;
        try {
            writer = new FileWriter(fileName);
            writer.write(content);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    public static void writeToFile(byte[] content, String fileName) throws IOException {
        File file = new File(fileName);
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));
        try {
            outputStream.write(content);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }

    public static String readStringFromFile(String fileName) throws IOException {
        FileReader reader = null;
        BufferedReader bufferedReader = null;
        try {
            reader = new FileReader(fileName);
            bufferedReader = new BufferedReader(reader);
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            return stringBuffer.toString();
        } finally {
            if (bufferedReader != null)
                bufferedReader.close();
            if (reader != null)
                reader.close();
        }
    }

    public static byte[] readByteFromFile(String fileName) throws IOException {
        BufferedInputStream inputStream = null;
        byte[] bytes;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(fileName));
            inputStream.available();
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return bytes;
        } finally {
            if (inputStream != null)
                inputStream.close();
        }
    }
}
